import React, { useState, useRef, useEffect } from 'react'
import { Sun, Moon, Monitor, Check } from 'lucide-react'
import { useThemeStore, Theme } from '@/stores/themeStore'
import { useTranslation } from '@/utils/i18n'

const ThemeSwitcher: React.FC = () => {
  const { theme, setTheme } = useThemeStore()
  const { t } = useTranslation()
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  const themes: { value: Theme; label: string; icon: React.ReactNode }[] = [
    { value: 'light', label: t('theme.light'), icon: <Sun size={16} /> },
    { value: 'dark', label: t('theme.dark'), icon: <Moon size={16} /> },
    { value: 'system', label: t('theme.system'), icon: <Monitor size={16} /> },
  ]

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  const getCurrentIcon = () => {
    const effectiveTheme = useThemeStore.getState().getEffectiveTheme()
    if (theme === 'light') return <Sun size={18} />
    if (theme === 'dark') return <Moon size={18} />
    return effectiveTheme === 'dark' ? <Moon size={18} /> : <Sun size={18} />
  }

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="p-2.5 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-all duration-200 relative group dark:hover:bg-gray-700 dark:text-gray-300"
        title={t('theme.light')}
      >
        {getCurrentIcon()}
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 py-2 z-50 animate-slide-up">
          {themes.map((themeOption) => (
            <button
              key={themeOption.value}
              onClick={() => {
                setTheme(themeOption.value)
                setIsOpen(false)
              }}
              className={`
                w-full flex items-center justify-between px-4 py-2.5 text-sm transition-colors
                ${theme === themeOption.value
                  ? 'bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400'
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                }
              `}
            >
              <div className="flex items-center gap-2">
                {themeOption.icon}
                <span>{themeOption.label}</span>
              </div>
              {theme === themeOption.value && (
                <Check size={16} className="text-blue-600 dark:text-blue-400" />
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  )
}

export default ThemeSwitcher

